<template>
  <div class="container">
    <!-- 选项卡tabs -->
    <el-tabs
      v-if="data.mounted"
      v-model="data.active"
      stretch
      type="border-card"
      @tab-change="handleTabChange"
    >
      <el-tab-pane label="审批信息" name="0">
        <FlowForm
          v-if="data.active === '0'"
          :defNodeId="props.currJob.defNodeId"
          :orderInstId="props.currJob.orderInstId"
          :readonly="props.readonly"
          :mode="props.currJob.defNodeFormMode"
        />
        <!-- 审批项 -->
        <el-form v-if="!readonly" label-width="80px" style="margin-top: 22px">
          <el-form-item label="审批意见:">
            <el-input
              v-model="data.comment"
              :autosize="{ minRows: 3, maxRows: 6 }"
              type="textarea"
              placeholder="请输入审批意见"
            />
          </el-form-item>
        </el-form>
        <div style="display: flex; justify-content: center">
          <span
            v-for="item in data.jobBtns"
            :key="item.type"
            style="
              padding: 0px 10px;
              display: flex;
              justify-content: center;
              align-items: center;
            "
          >
            <div
              v-if="methods.validateJobBtns(item.type)"
              style="padding: 0px 10px; display: flex; align-items: center"
            >
              <el-tooltip placement="top">
                <template #content>
                  {{ item.tips }}
                </template>
                <el-icon :size="18"><InfoFilled /></el-icon>
              </el-tooltip>
              <el-button
                :loading="data.loading"
                :disabled="data.loading"
                icon="Check"
                plain
                @click="methods.handleBtnClick(item)"
              >
                {{ item.desc }}
              </el-button>
            </div>
          </span>
        </div>
      </el-tab-pane>
      <el-tab-pane label="审批过程" name="1">
        <FlowComment
          v-if="data.active === '1'"
          :currJob="props.currJob"
          :show-close="false"
        />
      </el-tab-pane>
      <el-tab-pane label="审批进度" name="2">
        <FlowProgress
          v-if="data.active === '2'"
          :flow-inst-id="props.currJob.flowInstId"
        />
      </el-tab-pane>
      <el-tab-pane label="流程图" name="3">
        <FlowPhoto
          v-if="data.active === '3'"
          :def-flow-id="props.currJob.defFlowId"
          :flow-inst-id="props.currJob.flowInstId"
          :show-close="false"
        />
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      v-model="data.showChooseUser"
      top="20px"
      width="70%"
      append-to-body
      title="选择办理人"
    >
      <ChooseUser
        :node-user-type="data.nodeUserType"
        @confirm="methods.handleUserRoleConfirm"
      />
    </el-dialog>
    <el-dialog
      v-if="data.showToRunNode"
      v-model="data.showToRunNode"
      width="70%"
      title="选择任意驳回节点"
      append-to-body
    >
      <RunReject
        :curr-job="props.currJob"
        @confirm="methods.handleRejectConfirm"
      />
    </el-dialog>
    <el-dialog
      v-if="data.showJumpToRunNode"
      v-model="data.showJumpToRunNode"
      width="70%"
      title="选择任意跳转节点"
      append-to-body
    >
      <RunAnyJump
        :curr-job="props.currJob"
        @confirm="methods.handleJumpConfirm"
      />
    </el-dialog>
    <el-dialog
      v-if="data.showJobSignature"
      v-model="data.showJobSignature"
      width="70%"
      :title="data.jobSignatureTitle"
      append-to-body
    >
      <JobSignature
        :id="props.currJob.id"
        :curr-job="props.currJob"
        :flowInstId="props.currJob.flowInstId"
        :runNodeId="props.currJob.runNodeId"
        :signedType="data.signedType"
        @success="methods.handleJobSignatureSuccess"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="HandleJob">
import { useMessage, useMessageBox } from "@/hooks/message";
import * as jobTaskApi from "@/api/flow/jobtask";

// 引入组件
const FlowForm = defineAsyncComponent(
  () => import("@/components/flow/flowForm.vue")
);
const FlowComment = defineAsyncComponent(
  () => import("@/components/flow/flowComment.vue")
);
const FlowPhoto = defineAsyncComponent(
  () => import("@/components/flow/flowPhoto.vue")
);
const ChooseUser = defineAsyncComponent(
  () => import("@/components/flow/chooseUser.vue")
);
const RunReject = defineAsyncComponent(
  () => import("@/components/flow/flowReject.vue")
);
const RunAnyJump = defineAsyncComponent(
  () => import("@/components/flow/flowJump.vue")
);
const JobSignature = defineAsyncComponent(
  () => import("@/components/flow/flowJobSignature.vue")
);
const FlowProgress = defineAsyncComponent(
  () => import("@/components/flow/flowProgress.vue")
);

const props = defineProps({
  currJob: {
    type: Object,
    default: null
  },
  readonly: {
    type: Boolean,
    default: false
  }
});

const $emit = defineEmits(["complete"]);

const data = reactive({
  active: "0",
  jobBtns: [],
  loading: false,
  comment: "",
  showChooseUser: false,
  nodeUserType: undefined,
  nextUserRole: undefined,
  showJumpToRunNode: false,
  showToRunNode: false,
  showJobSignature: false,
  jobSignatureTitle: "",
  signedType: "",
  runNode: null,
  mounted: false
});

const initJobData = () => {
  data.loading = false;
  data.jobBtns = props.currJob.jobBtns;
  data.active = "0";
};

const handleTabChange = tabName => {
  data.active = tabName;
};

onMounted(() => {
  initJobData();
  nextTick(() => {
    data.mounted = true;
  });
});

const methods = {
  // 初始化数据
  handleUserRoleConfirm(userRole) {
    if (data.nodeUserType === "0") {
      methods.handleTurnConfirm(userRole);
    } else if (data.nodeUserType === "1") {
      methods.handleAssignNextConfirm(userRole);
    }
  },
  handleAssignNextConfirm(userOrRole) {
    useMessageBox()
      .confirm("是否确认指定下一办理人/角色?")
      .then(() => {
        data.nextUserRole = userOrRole;
        const params = {
          id: props.currJob.id,
          nextUserRole: data.nextUserRole
        };
        jobTaskApi.appointNextUser(params).then(res => {
          if (res.code === 200) {
            useMessage().success("操作成功");
            $emit("complete");
          } else {
            useMessage().error(res.msg);
          }
        });
      })
      .then(() => {
        data.showChooseUser = false;
      });
  },
  // 转办任务
  handleTurnConfirm(userOrRole) {
    useMessageBox()
      .confirm(`是否确认转办任务?`)
      .then(() => {
        const params = { id: props.currJob.id, userId: userOrRole };
        jobTaskApi.turnRunJob(params).then(res => {
          if (res.code === 200) {
            useMessage().success("转办成功");
            $emit("complete");
          } else {
            useMessage().error(res.msg);
          }
        });
      });
  },
  handleRejectConfirm(currJob) {
    data.showToRunNode = false;
    $emit("complete");
  },
  handleJobSignatureSuccess() {
    data.showJobSignature = false;
    $emit("complete");
  },
  handleJumpConfirm(currJob) {
    data.showJumpToRunNode = false;
    $emit("complete");
  },
  doHandleJob(jobBtn) {
    data.loading = true;
    //批准
    if (jobBtn.type === "0") {
      const params = {
        id: props.currJob.id,
        comment: data.comment
      };
      jobTaskApi.complete(params).then(res => {
        if (res.code === 200) {
          useMessage().success("审批成功");
          $emit("complete");
        } else {
          useMessage().error(res.msg);
        }
      });
    }
    //退回首节点
    else if (jobBtn.type === "1") {
      jobTaskApi
        .backFirstJob({ id: props.currJob.id, comment: data.comment })
        .then(res => {
          if (res.code === 200) {
            useMessage().success("驳回首节点成功");
            $emit("complete");
          } else {
            useMessage().error(res.msg);
          }
        });
    }
    // 退回上一步
    else if (jobBtn.type === "10") {
      jobTaskApi
        .backPreJob({ id: props.currJob.id, comment: data.comment })
        .then(res => {
          if (res.code === 200) {
            useMessage().success("驳回上一步成功");
            $emit("complete");
          } else {
            useMessage().error(res.msg);
          }
        });
    }
    //跳转
    else if (jobBtn.type === "8") {
      data.showJumpToRunNode = true;
    }
    //任意驳回
    else if (jobBtn.type === "2") {
      data.showToRunNode = true;
    }
    // 指定下一办理人
    else if (jobBtn.type === "3") {
      data.showChooseUser = true;
      data.nodeUserType = "1";
    }
    // 前加签
    else if (jobBtn.type === "5") {
      data.jobSignatureTitle = jobBtn.desc;
      data.signedType = "1";
      data.showJobSignature = true;
    }
    // 批准并后加签
    else if (jobBtn.type === "6") {
      data.jobSignatureTitle = jobBtn.desc;
      data.signedType = "2";
      data.showJobSignature = true;
    }
    // 转办
    else if (jobBtn.type === "11") {
      data.showChooseUser = true;
      data.nodeUserType = "0";
    }
    data.loading = false;
  },
  // 提交任务
  async handleBtnClick(jobBtn) {
    const loadingInstance = ElLoading.service();
    methods.doHandleJob(jobBtn);
    loadingInstance.close();
  },
  validateJobBtns(jobBtnType) {
    let status = props.currJob.runNodeStatus;
    let next = true;
    if (status === "9") {
      //批准
      return jobBtnType === "0";
    } else if (next) {
      //批准并指定下一办理人
      return (jobBtnType === "3" && next) || jobBtnType !== "3";
    } else {
      //批准并指定下一办理人
      return jobBtnType !== "3";
    }
  }
};
</script>

<style lang="scss" scoped></style>
